left
详情
主题:Hibernate 多对一例子 返回 搜索

StudentEntity.java


package cc.www.hibernatedemo.model;

public class StudentEntity {
  private int id;
  private String sname;
  private TeacherEntity teacherId;

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getSname() {
    return sname;
  }

  public void setSname(String sname) {
    this.sname = sname;
  }

  public TeacherEntity getTeacherId() {
    return teacherId;
  }

  public void setTeacherId(TeacherEntity teacherId) {
    this.teacherId = teacherId;
  }

  public StudentEntity(String sname) {
    this.sname = sname;
  }

  public StudentEntity() {
  }

  @Override
  public String toString() {
    return "StudentEntity [id=" + id + ", sname=" + sname + ", teacherId=" + teacherId + "]";
  }

}


TeacherEntity.java



package cc.www.hibernatedemo.model;

import java.util.HashSet;
import java.util.Set;

public class TeacherEntity {
    private int id;
    private String tname;
    
    //一对多
    private Set<StudentEntity> students=new HashSet<StudentEntity>();
    
    
  @Override
  public String toString() {
    return "TeacherEntity [id=" + id + ", tname=" + tname + "]";
  }
  public String getTname() {
    return tname;
  }
  public void setTname(String tname) {
    this.tname = tname;
  }
  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
  public TeacherEntity(String tname) {
    this.tname = tname;
  }
  
  public TeacherEntity() {
  }
  public Set<StudentEntity> getStudents() {
    return students;
  }
  public void setStudents(Set<StudentEntity> students) {
    this.students = students;
  }
   
}



StudentEntity.hbm.xml



<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2019-12-28 15:20:08 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
    <class name="cc.www.hibernatedemo.model.StudentEntity" table="t_student">
        <id name="id" type="int">
            <column name="id" />
            <generator class="native" />
        </id>
        <property name="sname" type="java.lang.String">
            <column name="s_name" />
        </property>
        <many-to-one name="teacherId" class="cc.www.hibernatedemo.model.TeacherEntity" fetch="join">
            <column name="teacher_id" />
        </many-to-one>
    </class>
</hibernate-mapping>



TeacherEntity.hbm.xml



<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2019-12-28 15:20:08 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
    <class name="cc.www.hibernatedemo.model.TeacherEntity" table="t_teacher">
        <id name="id" type="int">
            <column name="id" />
            <generator class="native" />
        </id>
        <property name="tname" type="java.lang.String">
            <column name="t_name" />
        </property>
        <!-- 表名要与学生表对应 -->
        <set name="students" table="t_students">
          <key>
            <column name="teacher_id"></column>
          </key>          
          <one-to-many class="cc.www.hibernatedemo.model.StudentEntity"/>
        </set>
    </class>
</hibernate-mapping>




hibernate.cfg.xml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                                         "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/hibernateproject?characterEncoding=utf8&amp;amp;useSSL=false</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">123456</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.format_sql">true</property>


    <!-- 选择使用C3P0连接池 -->
    <property name="hibernate.connection.provider_class">org.hibernate.c3p0.internal.C3P0ConnectionProvider</property>
    <!-- 最大连接数 -->
    <property name="hibernate.c3p0.max_size">20</property>
    <!-- 最小连接数 -->
    <property name="hibernate.c3p0.min_size">5</property>
    <!-- 获得连接的超时时间,如果超过这个时间,会抛出异常,单位毫秒 -->
    <property name="hibernate.c3p0.timeout">120</property>
    <!-- 最大的PreparedStatement的数量 -->
    <property name="hibernate.c3p0.max_statements">100</property>
    <!-- 每隔120秒检查连接池里的空闲连接 ,单位是秒 -->
    <property name="hibernate.c3p0.idle_test_period">120</property>
    <!-- 当连接池里面的连接用完的时候,C3P0一下获取的新的连接数 -->
    <property name="hibernate.c3p0.acquire_increment">2</property>
    <!-- 每次都验证连接是否可用 -->


    <property name="hibernate.c3p0.validate">true</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <mapping class="cc.www.hibernatedemo.model.StudentEntity" />
    <mapping
      resource="cc/www/hibernatedemo/model/StudentEntity.hbm.xml" />
    <mapping class="cc.www.hibernatedemo.model.TeacherEntity" />
    <mapping
      resource="cc/www/hibernatedemo/model/TeacherEntity.hbm.xml" />
  </session-factory>
</hibernate-configuration>




hibernate.cfg.xml


package cc.www.hibernatedemo.model;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.Date;

@SuppressWarnings("unused")
public class StudentEntityTest {
    private SessionFactory sessionFactory=null;
    private Session session =null;
    private Transaction transaction =null;
    
    
    @Before
    public void init(){
      //测试同步
        //System.out.println("开始测试文件");
        //返回的configureation,包含有配置文件里的具体信息
      
        Configuration configure = new Configuration().configure();
        //创建一个SessionFactory工厂类,通过它建立一个数据库连接会话,Session
        sessionFactory= configure.buildSessionFactory();
        
        //通过工厂类开启Session对
        session = sessionFactory.openSession();
        //开始事务
        transaction = session.beginTransaction();
    }
    
    
    @After
    public void destroy(){
        //System.out.println("结束");
        //提交事务
        transaction.commit();
        //关闭
        session.close();
        //关闭工厂
        sessionFactory.close();
    }
    
    
    @Test
    public void test() {
        //增加
        //执行数据库操作,用面向对象方式来操作数据库
        TeacherEntity teacherEntity = new TeacherEntity();
        teacherEntity.setTname("黄老师");
        session.save(teacherEntity);
        
        StudentEntity studentEntity1 = new StudentEntity();
        studentEntity1.setSname("张三");
        studentEntity1.setTeacherId(teacherEntity);

        StudentEntity studentEntity2 = new StudentEntity();
        studentEntity2.setSname("李四");
        studentEntity2.setTeacherId(teacherEntity);

        session.save(studentEntity1);
        session.save(studentEntity2);
        
        
        //查询
//        StudentEntity studentEntity=session.get(StudentEntity.class,1);
//        System.out.println(studentEntity);
//        System.out.println(studentEntity.getTeacherId().getTname());
        //修改
//        StudentEntity studentEntity=session.get(StudentEntity.class,1);
//        studentEntity.setSname("小张");
      //删除
//        StudentEntity studentEntity=session.get(StudentEntity.class,1);
//        session.delete(studentEntity);

    }
}
警告:
您是否确定删除贴子?
确定 取消
copyright